﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using CoreEx.Database.Client;
using LinFu.AOP.Interfaces;
using LinFu.IoC.Configuration;

namespace CoreEx.Database.Linq.Tests
{
    [Implements(typeof(IProfiler<IDbCommand>), LifecycleType.OncePerThread)]
    public class ConsoleDbCommandProfiler : IProfiler<IDbCommand>
    {
        private Stopwatch _stopwatch;

        public long TimeElapsed { get; set; }

        public void BeforeInvoke(IInvocationInfo info)
        {
            if (info.TargetMethod.Name == "ExecuteReader")
            {
                _stopwatch = new Stopwatch();
                if (((IDbCommand)info.Target).CommandText.Contains("TABLE_CATALOG"))
                    return;
                Console.WriteLine("**********************************************************************************************************");
                Console.WriteLine("Statement:");
                Console.WriteLine();
                Console.WriteLine(((IDbCommand)info.Target).CommandText);
                Console.WriteLine();
                Console.WriteLine("**************************************************");
                Console.WriteLine("Parameters:");
                Console.WriteLine();
                foreach (var parameter in ((IDbCommand)info.Target).Parameters.Cast<IDataParameter>())
                {
                    Console.WriteLine(string.Format("Name: {0}  Value: {1}", parameter.ParameterName, parameter.Value));
                }

                _stopwatch.Start();
            }
        }

        public void AfterInvoke(IInvocationInfo info, object returnValue)
        {
            if (info.TargetMethod.Name == "ExecuteReader")
            {
                _stopwatch.Stop();
                TimeElapsed = _stopwatch.ElapsedMilliseconds;




                Console.WriteLine(string.Format("Executed in {0} milliseconds ", TimeElapsed));


            }
        }
    }
}
